#!/usr/bin/env node

const path = require('path');
const inquirer = require('inquirer');
const fs = require('node-fs-extra');
const ejs = require('ejs');

const destDir = process.cwd();
const tmpDir = path.join(__dirname, 'templates');
const excludeFiles = ['.DS_Store']

async function getConfig () {
    try {
        const answers = await inquirer.prompt({
            type: 'input',
            name: 'projectName',
            message: '请输入项目名称',
            default: 'vue-ycli-project'
        });
        return answers;
    } catch (err) {
        //
    }
}

function getAllFiles (dir, baseDir = '', files = []) {
    const curFiles = fs.readdirSync(dir);
    curFiles.forEach(file => {
        if (excludeFiles.includes(file)){ return; }
        const curDir = path.join(dir, file);
        const bsDir = path.join(baseDir, file);
        const stat = fs.statSync(curDir);
        if (stat.isDirectory()) {
            getAllFiles(curDir, bsDir, files);
        } else {
            files.push(bsDir);
        }
    })
    return files;
}

async function ejsTransformAndCopy (files, answers) {
    const rootDirName = answers.projectName;
    files.forEach(file => {
        ejs.renderFile(path.join(tmpDir, file), answers, (err, result) => {
            if (err) { throw err }
            fs.outputFileSync(path.join(destDir, rootDirName, file), result)
        })
    })
}

async function main () {
    try {
        const answers = await getConfig();
        const allFiles = getAllFiles(tmpDir);
        await ejsTransformAndCopy(allFiles, answers);
    } catch (err) {
        console.log('err：' + err);
    }
}

main();
